package net.cardgame.orcalecard;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jp.jma.oraclecard.MyApplication;
import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.common.ImageClickable;
import net.cardgame.oraclecard.common.ThreadLoadImage;
import net.cardgame.orcalecard.bean.CardBean;
import net.cardgame.orcalecard.bean.HistoryBean;
import net.cardgame.orcalecard.bean.NewsBean;
import net.cardgame.orcalecard.pref.SecurePreferences;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.KeyboardHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.novoda.imageloader.core.ImageManager;
import com.novoda.imageloader.core.model.ImageTagFactory;

public class SaveHistoryActivity extends Activity implements OnClickListener {
	ImageClickable card1, card2, card3, card4;
	ImageView img_bg, img_deck, btnSave, btnShareFacebook;
	EditText txtQuestion, txtMemory;
	TextView txtDateTime, txtTitle;
	int number_of_card, card1Id, card2Id, card3Id, card4Id, deckId;
	String question;
	ArrayList<CardBean> listCardBean;
	Date datetime;
	String strDatetime;
	CardBean cardBean1;
	CardBean cardBean2;
	CardBean cardBean3;
	CardBean cardBean4;
	boolean saved = false;
	boolean flag = true;
	ImageView frame2, frame3, frame4;
	private ImageManager imageManager;
	private ImageTagFactory imageTagFactory;
	private SecurePreferences contentPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.save_sharefacebook_activity);
		contentPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		initImageLoader();
		setupUI(findViewById(R.id.parent));
		ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView1);
		scrollView.setFadingEdgeLength(0);
		findViewById(R.id.btn_back_save).setOnClickListener(this);
		findViewById(R.id.btn_help_save).setOnClickListener(this);
		frame2 = (ImageView) findViewById(R.id.img_frame_card2);
		frame3 = (ImageView) findViewById(R.id.img_frame_card3);
		frame4 = (ImageView) findViewById(R.id.img_frame_card4);
		btnSave = (ImageView) findViewById(R.id.btn_save);
		btnShareFacebook = (ImageView) findViewById(R.id.btn_sharefacebook);
		btnShareFacebook.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		txtTitle = (TextView) findViewById(R.id.txttitle_deck_save);
		card1 = (ImageClickable) findViewById(R.id.img_card1_save);
		card2 = (ImageClickable) findViewById(R.id.img_card2_save);
		card3 = (ImageClickable) findViewById(R.id.img_card3_save);
		card4 = (ImageClickable) findViewById(R.id.img_card4_save);
		img_bg = (ImageView) findViewById(R.id.img_bg_save);
		img_deck = (ImageView) findViewById(R.id.img_deck_save);
		txtQuestion = (EditText) findViewById(R.id.txtquestion_save);
		txtMemory = (EditText) findViewById(R.id.txtmemory_save);
		txtDateTime = (TextView) findViewById(R.id.txt_datetime_save);
		getExtra();
		loadImage();
	}

	void getExtra() {
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		deckId = bundle.getInt("deckId");
		number_of_card = bundle.getInt("number_of_card");
		question = bundle.getString("question");
		cardBean1 = bundle.getParcelable("cardBean1");
		cardBean2 = bundle.getParcelable("cardBean2");
		cardBean3 = bundle.getParcelable("cardBean3");
		cardBean4 = bundle.getParcelable("cardBean4");
		listCardBean = new ArrayList<CardBean>();
		listCardBean.add(cardBean1);
		listCardBean.add(cardBean2);
		listCardBean.add(cardBean3);
		listCardBean.add(cardBean4);
	}

	private Handler handlerLoadImage = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				card1.setImageDrawable((Drawable) msg.obj);
				card1.setOnClickListener(SaveHistoryActivity.this);
				break;
			case 2:
				card2.setImageDrawable((Drawable) msg.obj);
				card2.setOnClickListener(SaveHistoryActivity.this);
				frame2.setVisibility(View.INVISIBLE);
				break;
			case 3:
				card3.setImageDrawable((Drawable) msg.obj);
				card3.setOnClickListener(SaveHistoryActivity.this);
				frame3.setVisibility(View.INVISIBLE);
				break;
			case 4:
				card4.setImageDrawable((Drawable) msg.obj);
				card4.setOnClickListener(SaveHistoryActivity.this);
				frame4.setVisibility(View.INVISIBLE);
				break;
			case 5:
				img_bg.setImageDrawable((Drawable) msg.obj);
				break;
			default:
				break;
			}
		};
	};

	void loadImage() {
		ImageView img_number_card = (ImageView) findViewById(R.id.img_number_of_card_save);
		// Set text question
		if (question != null)
			txtQuestion.setText(question);
		displayDateTime();
		// load DeckTitle
		if (deckId == 999) {
			txtTitle.setText(R.string.title_special);
			img_bg.setImageResource(R.drawable.bg999);
			img_deck.setImageResource(R.drawable.c999i);
		} else {
			String key = "content_" + deckId;
			String deckName;
			if (contentPreferences.containsKey(key)) {
				deckName = contentPreferences.getString(key);
				String[] arr = deckName.split("---");
				deckName = arr[0];
				if (deckName.contains("←"))
					deckName = deckName.substring(0, deckName.indexOf("←"));
				txtTitle.setText(deckName);
			}

			// Load BackGround image
			new ThreadLoadImage(this, handlerLoadImage,
					ConstantValue.getPatchCardData(this) + "Card_"
							+ convertIdToStringId(deckId) + "/en_bg"
							+ convertIdToStringId(deckId) + ".jpg", img_bg, 5)
					.start();
			String pathImageDeck = ConstantValue.BASE_URL + "Card_"
					+ convertIdToStringId(deckId) + "/c"
					+ convertIdToStringId(deckId) + "i.png";
			setImageTag(img_deck, pathImageDeck);
			loadImage(img_deck);
		}
		// load card1
		loadCard1();
		// Load card 2,3,4
		switch (number_of_card) {
		case 3:
			loadCard2();
			loadCard3();
			img_number_card.setImageResource(R.drawable.result_draw3);
			break;
		case 4:
			loadCard2();
			loadCard3();
			loadCard4();
			img_number_card.setImageResource(R.drawable.result_draw4);
			break;

		default:
			break;
		}
		// Load Jump Card
		findViewById(R.id.img_jump_card1_save).setVisibility(
				listCardBean.get(0).isJump ? View.VISIBLE : View.INVISIBLE);
		findViewById(R.id.img_jump_card2_save).setVisibility(
				listCardBean.get(1).isJump ? View.VISIBLE : View.INVISIBLE);
		findViewById(R.id.img_jump_card3_save).setVisibility(
				listCardBean.get(2).isJump ? View.VISIBLE : View.INVISIBLE);
		findViewById(R.id.img_jump_card4_save).setVisibility(
				listCardBean.get(3).isJump ? View.VISIBLE : View.INVISIBLE);
	}

	// Load card1
	void loadCard1() {
		String path = getCardPatchByCardId(listCardBean.get(0));
		card1.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, card1, 1).start();
	}

	void loadCard2() {
		String path = getCardPatchByCardId(listCardBean.get(1));
		card2.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, card2, 2).start();
		card2.setVisibility(View.VISIBLE);
	}

	void loadCard3() {
		String path = getCardPatchByCardId(listCardBean.get(2));
		card3.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, card3, 3).start();
		card3.setVisibility(View.VISIBLE);
	}

	void loadCard4() {
		String path = getCardPatchByCardId(listCardBean.get(3));
		card4.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, card4, 4).start();
		card4.setVisibility(View.VISIBLE);
	}

	/**
	 * display get card datetime
	 */
	void displayDateTime() {
		Calendar c = Calendar.getInstance();
		datetime = c.getTime();

		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		int hh = c.get(Calendar.HOUR_OF_DAY);
		int mm = c.get(Calendar.MINUTE);
		String dayWeek = "";
		switch (dayOfWeek) {
		case 2:
			dayWeek = "Mon";
			break;
		case 3:
			dayWeek = "Tue";
			break;
		case 4:
			dayWeek = "Wed";
			break;
		case 5:
			dayWeek = "Thu";
			break;
		case 6:
			dayWeek = "Fri";
			break;
		case 7:
			dayWeek = "Sat";
			break;
		case 8:
			dayWeek = "Sun";
			break;
		default:
			break;
		}
		strDatetime = year + "年" + convertIdToStringId(month) + "月"
				+ convertIdToStringId(day) + "日(" + dayWeek + ") "
				+ convertIdToStringId(hh) + ":" + convertIdToStringId(mm);
		txtDateTime.setText(strDatetime);
	}

	String convertIdToStringId(int id) {
		return id < 10 ? "0" + id : "" + id;
	}

	/**
	 * Get patch image file
	 * 
	 * @param id
	 *            cardId
	 * @return patch to image
	 */
	String getCardPatchByCardId(int id) {
		return ConstantValue.getPatchCardData(this) + "Card_"
				+ convertIdToStringId(deckId) + "/X3/en_c"
				+ convertIdToStringId(deckId) + convertIdToStringId(id)
				+ ".png";
	}

	String getCardPatchByCardId(CardBean cardBean) {
		return ConstantValue.getPatchCardData(this) + "Card_"
				+ convertIdToStringId(cardBean.deckId) + "/X3/en_c"
				+ convertIdToStringId(cardBean.deckId)
				+ convertIdToStringId(cardBean.cardId) + ".png";
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (!flag)
			return;
		else
			flag = false;
		switch (v.getId()) {
		case R.id.btn_back_save:
			this.finish();
			break;
		case R.id.btn_help_save:
			Intent intent = new Intent(this, HelpActivity.class);
			intent.putExtra(HelpActivity.KEY_HELP_INDEX, 10);
			startActivityForResult(intent, ConstantValue.SAVE_HISTORY_ACTIVITY);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			break;
		case R.id.btn_save:
			if (!saved) {
				saved = true;
				btnSave.setSelected(true);
				saveHistory();
			}
			flag = true;
			break;
		case R.id.btn_sharefacebook:
			gotoPostFacebook();
			break;
		case R.id.img_card1_save:
			gotoCardDetail(listCardBean.get(0));
			break;
		case R.id.img_card2_save:
			gotoCardDetail(listCardBean.get(1));
			break;
		case R.id.img_card3_save:
			gotoCardDetail(listCardBean.get(2));
			break;
		case R.id.img_card4_save:
			gotoCardDetail(listCardBean.get(3));
			break;
		default:
			break;
		}

	}

	void gotoPostFacebook() {
		Intent intent = new Intent(this, PostFacebookActivity.class);
		intent.putExtra("number_of_card", number_of_card);
		intent.putExtra("deckId", deckId);
		intent.putExtra("cardBean1", cardBean1);
		intent.putExtra("cardBean2", cardBean2);
		intent.putExtra("cardBean3", cardBean3);
		intent.putExtra("cardBean4", cardBean4);
		startActivityForResult(intent, 0);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	void gotoCardDetail(CardBean cardBean) {
		Intent intent = new Intent(this, CardDetailActivity.class);
		intent.putExtra("deckId", cardBean.deckId);
		intent.putExtra("cardId", cardBean.cardId);
		startActivityForResult(intent, ConstantValue.SAVE_HISTORY_ACTIVITY);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	/**
	 * save history get card to shared reference
	 */
	void saveHistory() {
		List<HistoryBean> listHistory = null;
		Gson gson = new Gson();
		Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() {
		}.getType();
		SecurePreferences appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		if (appPreferences.containsKey(ConstantValue.HISTORY_KEY)) {
			String strHistory = appPreferences
					.getString(ConstantValue.HISTORY_KEY);
			listHistory = gson.fromJson(strHistory, listOfHistoryBean);

		}
		if (listHistory == null) {
			listHistory = new ArrayList<HistoryBean>();
		}
		int size = listHistory.isEmpty() ? 0 : listHistory.size();
		HistoryBean history = new HistoryBean();
		if (size == 0)
			history.id = 1;
		else {
			history.id = listHistory.get(size - 1).id + 1;
			if (size == 100) {
				String sumary = "保存件数が 100件に達しているため、今回の結果は保存できません。\n"
						+ " 次回以降新しく保存したい場合は保存したデータを削除して空きスペースを作って\n ください";
				showDialog(null, sumary, true);
			}
		}
		history.deckbeanId = deckId;
		history.question = txtQuestion.getText().toString();
		String memo = txtMemory.getText().toString();
		if (!memo.matches("")) {
			ArrayList<NewsBean> listNews = new ArrayList<NewsBean>();
			NewsBean newsBean = new NewsBean();
			newsBean.id = 1;
			newsBean.datetime = strDatetime;
			newsBean.time = datetime;
			newsBean.sumary = memo;
			listNews.add(newsBean);
			history.newsBeans = listNews;
		}
		history.datetime = datetime;
		history.strDateTime = strDatetime;
		history.deckTitle = txtTitle.getText().toString();
		history.cardBeans = getListCardBean();
		listHistory.add(history);
		String save = gson.toJson(listHistory, listOfHistoryBean);
		appPreferences.put(ConstantValue.HISTORY_KEY, save);
		size++;
		if (size == 100) {
			String title = "保存件数が 100件に達しました。これ以上保存できません。\n新しく保存したい場合は保存したデータを削除して空きスペースを作ってくださ  い";
			String sumary = "100件保存状態の場合「保存」したら\n"
					+ "「保存件数が 100件に達しているため、今回の結果は保存できません。\n"
					+ "次回以降新しく保存したい場合は保存したデータを削除して空きスペース\n" + "を作ってください」\n"
					+ "と表示し、保存しない。";
			showDialog(title, sumary, true);
		} else if (size > 90) {
			int add = 100 - size;
			String title = "保存可能件数は残り" + add + "件です";
			showDialog(title, null, false);
		} else {
			String title = "本体に保 存しました";
			showDialog(title, null, false);
		}
	}

	/**
	 * Show dialog when save history
	 * 
	 * @param title
	 *            Title of dialog
	 * @param sumary
	 *            message of dialog
	 * @param fullHistory
	 *            true if history record =100
	 */
	void showDialog(String title, String sumary, boolean fullHistory) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView myMsg = new TextView(this);
		myMsg.setText(title);
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		myMsg.setTextSize(20);
		myMsg.setTextColor(Color.WHITE);
		// set custom title
		builder.setCustomTitle(myMsg);
		builder.setMessage(sumary);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
				flag = true;
			}
		});
		AlertDialog dialog = builder.show();
		// Create custom message
		TextView messageText = (TextView) dialog
				.findViewById(android.R.id.message);
		if (messageText != null)
			messageText.setGravity(Gravity.CENTER);
	}

	/**
	 * @return list card bean to save history
	 */
	private ArrayList<CardBean> getListCardBean() {
		switch (number_of_card) {
		case 1:
			CardBean cardBean = listCardBean.get(0);
			listCardBean = new ArrayList<CardBean>();
			listCardBean.add(cardBean);
			break;
		case 3:
			listCardBean.remove(3);
			break;
		default:
			break;
		}
		return listCardBean;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		flag = true;
	}

	public void setupUI(View view) {
		// Set up touch listener for non-text box views to hide keyboard.
		if (!(view instanceof EditText)) {

			view.setOnTouchListener(new OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					v.requestFocus();
					KeyboardHelper.hideSoftKeyboard(SaveHistoryActivity.this);
					return false;
				}

			});
		}

		// If a layout container, iterate over children and seed recursion.
		if (view instanceof ViewGroup) {

			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

				View innerView = ((ViewGroup) view).getChildAt(i);

				setupUI(innerView);
			}
		}
	}

	private void initImageLoader() {
		imageManager = MyApplication.getInstance().getImageLoader();
		imageTagFactory = createImageTagFactory();
	}

	private ImageTagFactory createImageTagFactory() {
		ImageTagFactory imageTagFactory = ImageTagFactory.newInstance();
		imageTagFactory.setHeight(248);
		imageTagFactory.setWidth(188);
		imageTagFactory.setDefaultImageResId(R.drawable.cardi_tranparent);
		imageTagFactory.setErrorImageId(R.drawable.cardi_tranparent);
		imageTagFactory.setSaveThumbnail(true);
		return imageTagFactory;
	}

	private void setImageTag(ImageView view, String url) {
		view.setTag(imageTagFactory.build(url, this));
	}

	private void loadImage(ImageView view) {
		imageManager.getLoader().load(view);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		super.onBackPressed();
	}
}
